package com.suning.sawp.service.impl.bi;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.suning.framework.dal.client.DalClient;
import com.suning.sawp.cache.RedisClient;
import com.suning.sawp.constants.BiRealTimeConstants;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.bi.BiSaleAmountDto;
import com.suning.sawp.dto.bi.BiStoreAvgPrice;
import com.suning.sawp.dto.bi.BiStoreCateSaleCompleteRateDto;
import com.suning.sawp.dto.bi.BiStoreCateSaleDataDayDto;
import com.suning.sawp.dto.bi.BiStoreCateSaleDayDto;
import com.suning.sawp.dto.bi.BiStoreJxcBrandDetail;
import com.suning.sawp.dto.bi.BiStoreJxcCateInfo;
import com.suning.sawp.dto.bi.BiStoreSaleBrandAvgPricedDetailsDto;
import com.suning.sawp.dto.bi.BiStoreSaleBrandAvgPricedDto;
import com.suning.sawp.dto.bi.BiStoreSaleDayDto;
import com.suning.sawp.dto.bi.BiStoreYbInfoDto;
import com.suning.sawp.dto.bi.BiStoreYbMonthDto;
import com.suning.sawp.dto.bi.sale.IndexCockpitDto;
import com.suning.sawp.dto.bi.sale.IndexCockpitRetGdsDto;
import com.suning.sawp.dto.bi.sale.IndexCockpitSaleNoPick;
import com.suning.sawp.dto.bi.sale.SaleCategory;
import com.suning.sawp.dto.bi.sale.StoreCateMonthSaleDataDto;
import com.suning.sawp.dto.bi.sale.StoreCateMonthSaleDto;
import com.suning.sawp.dto.bi.sale.StoreGuideIndexDay;
import com.suning.sawp.dto.bi.sale.StoreGuideIndexMonth;
import com.suning.sawp.dto.bi.sale.StoreGuideSaleCompleteRate;
import com.suning.sawp.dto.bi.sale.StoreMaxSaleBrandMDto;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.returngoods.StoreOosHomeShowDto;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.dto.yxwt.CateInfo;
import com.suning.sawp.intf.bi.BiBrandDaoService;
import com.suning.sawp.intf.bi.BiBrandService;
import com.suning.sawp.intf.bi.BiCmmdtyService;
import com.suning.sawp.intf.bi.BiKafkaRealTimeSaleService;
import com.suning.sawp.intf.bi.BiSaleAmountDaoService;
import com.suning.sawp.intf.bi.StoreGuideBiService;
import com.suning.sawp.intf.model.ModelAnalyseService;
import com.suning.sawp.intf.model.vo.SummaryContributionVo;
import com.suning.sawp.intf.returngoods.StoreOosService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.intf.yxwt.SaledNoTakeService;
import com.suning.sawp.po.bi.BIStoreSaleCateDay;
import com.suning.sawp.po.bi.BiBrandSale;
import com.suning.sawp.po.bi.BiStoreCateBrandDay;
import com.suning.sawp.po.bi.BiStoreRetGdsHomeVo;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;

@Service
public class StoreGuideBiServiceImpl implements StoreGuideBiService {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoreGuideBiServiceImpl.class);
    
    @Resource
    StoreManService storeManService;
    
    @Resource 
    BiSaleAmountDaoService biSaleAmountDaoService;
    
    @Resource
    BiKafkaRealTimeSaleService biKafkaRealTimeSaleService;
    
    @Resource
    BiStoreRetGdsHomeService biStoreRetGdsHomeService;
    
    @Resource
    StoreOosService storeOosService;
    
    @Resource
    ModelAnalyseService modelAnalyseService;
    
    @Resource
    SaledNoTakeService saledNoTakeService;
    
    @Resource
    BiBrandService biBrandService;
    
    @Autowired
    DalClient dalClient;
    
    @Resource
    BiBrandDaoService biBrandDaoService;
	
	@Autowired
    RedisClient redisClient;
	
	@Resource
	BiCmmdtyService biCmmdtyService;
	
    /**
     * 按销售额排序
     */
    private static final String ORDER_BY_AMOUNT = "0";
    
    /**
     * 第一个
     */
    private static final int FIRST_ELE = 0;
    
    
    /**
     * 品牌最多显示20条
     */
    private static final int BRAND_MAX_SHOW_NUM = 20;
    
    @Override
    public ReturnMsg<StoreGuideIndexDay> getStoreGuideIndexDay(String staffId, String cateCode) {
        LOGGER.info("getStoreGuideIndexDay in staffId:{}， cateCode:{}", staffId, cateCode);
        ReturnMsg<StoreGuideIndexDay> returnMsg = new ReturnMsg<StoreGuideIndexDay>();
        // 查询工号对应人员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(staffId);
        // 检验此工号是否为督导，以及cateCode是否属于此人
        if (null != manDto && ClerkConstants.SALE_GUIDE.equals(manDto.getPositionId())
                && CollectionUtils.isNotEmpty(manDto.getCategories())) {
            // 没有传品类编码，默认取此工号的第一个品类
            String categoryCd = StringUtils.isBlank(cateCode) 
                    ? manDto.getCategories().get(0).getCategoryCode() : cateCode;
            if (!manDto.validHasCate(categoryCd)) {
                // 判断品类编码归属于此工号,不属于报参数异常
                returnMsg.setError(ErrorCodeConstants.ERR_0001);
                return returnMsg;
            }
            
            // 参数校验通过，设置督导所属品类信息
            StoreGuideIndexDay indexDay = new StoreGuideIndexDay();
            List<SaleCategory> categories = new ArrayList<SaleCategory>();
            for (Category category : manDto.getCategories()) {
                SaleCategory saleCategory = new SaleCategory();
                saleCategory.setCateCode(category.getCategoryCode());
                saleCategory.setCateName(category.getCategoryName());
                saleCategory.setChooseStatus(categoryCd.equals(category.getCategoryCode())
                        ? SaleCategory.ChooseStatus.YES : SaleCategory.ChooseStatus.NO);
                categories.add(saleCategory);
            }
            indexDay.setCategories(categories);
            // 取月度销售任务及离线的月度销售额
            String month = DateUtils.getThisMonth();
            StoreCateMonthSaleDto monthSaleDto = biSaleAmountDaoService.queryStoreCateMonthSale(month, categoryCd, manDto.getStoreCode());
            // 月度销售额 = 截止至昨日的离线销售+今日实时销售
            Map<String, Object> realTimeMap = biKafkaRealTimeSaleService.getStoreCateSaleDataFromRedis(
                    manDto.getStoreCode(), categoryCd);
            // 今日实时销售
            BigDecimal todaySaleAmount = new BigDecimal(0);
            if (null != realTimeMap && null != realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT)) {
                todaySaleAmount = new BigDecimal((Double) realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT));
            }
            BigDecimal saleAmount = todaySaleAmount.add(null != monthSaleDto.getSaleAmount()
                    ? monthSaleDto.getSaleAmount() : new BigDecimal(0));
            // 本月销售额
            indexDay.setSaleAmount(BiSaleAmountDto.valueOf(saleAmount));
            // 本月任务毛利额
            indexDay.setTaskGrossProfit(BiSaleAmountDto.valueOf(monthSaleDto.getTaskGrossProfit()));
            // 本月任务销售额
            indexDay.setTaskSaleAmount(BiSaleAmountDto.valueOf(monthSaleDto.getTaskSaleAmount()));
            // 月度销售完成率
            indexDay.setSaleCompleteRate(DJStringUtils.calculateRatePercent(saleAmount, monthSaleDto.getTaskSaleAmount()).toString());
            // 月度剩余差额
            indexDay.setSyce(getSyce(saleAmount, monthSaleDto.getTaskSaleAmount()));
            // 今日客单价  今日实时销售/今日购买人数
            BigDecimal custAvgPrice = new BigDecimal("0.00");
            if (null != realTimeMap && null != realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.CUST_NUM)) {
                BigDecimal custNum = new BigDecimal((Double) realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.CUST_NUM));
                custAvgPrice = custNum.compareTo(new BigDecimal(0)) == 0 ? new BigDecimal("0.00") : DJStringUtils.divide(todaySaleAmount,custNum);
            }
            indexDay.setTodayCustAvgPrice(BiSaleAmountDto.valueOfLow(custAvgPrice));
            // 今日客单价同比
            BigDecimal todayCustAvgPriceYoy = biKafkaRealTimeSaleService.getStoreCateCustAvgPriceYoy(manDto.getStoreCode(), categoryCd);
            indexDay.setTodayCustAvgPriceYoy(null != todayCustAvgPriceYoy ? todayCustAvgPriceYoy.toString() : "");
            // 获取今日品类下销冠数据
            Map<String, Object> maxMap = getTodayMaxBrand(manDto.getStoreCode(), categoryCd);
            // 今日销冠品牌销售额
            BigDecimal brandSaleAmount = new BigDecimal("0.00");
            // 今日销冠品牌编码
            String todayMaxBrandCode = "";
            // 今日销冠品牌名称  
            String todayMaxBrandName = "";
            if (null != maxMap) {
                // 今日销冠品牌销售额
                if (null != maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.SALE_AMOUNT)) {
                    brandSaleAmount = new BigDecimal((Double) maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.SALE_AMOUNT));
                }
                // 今日销冠品牌编码
                if (null != maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.BRAND_CODE)) {
                    todayMaxBrandCode = (String) maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.BRAND_CODE);
                }
                // 今日销冠品牌名称  
                if (null != maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.BRAND_NAME)) {
                    todayMaxBrandName = (String) maxMap.get(BiRealTimeConstants.StoreCateBrandAttributes.BRAND_NAME);
                }
            }
            indexDay.setTodayMaxBrandCode(todayMaxBrandCode);
            indexDay.setTodayMaxBrandName(todayMaxBrandName);
            indexDay.setTodayMaxBrandAmount(BiSaleAmountDto.valueOf(brandSaleAmount));
            // 今日销售额
            indexDay.setTodaySaleAmount(BiSaleAmountDto.valueOf(todaySaleAmount));
            // 今日销售同比
            BigDecimal todaySaleAmountYoy = biKafkaRealTimeSaleService.getStoreCateSaleAmountYoy(manDto.getStoreCode(), categoryCd);
            indexDay.setTodaySaleAmountYoy(todaySaleAmountYoy == null ? "" : todaySaleAmountYoy.toString());
            // 获取昨日品类销售数据
            Set<String> categoryCodes = new HashSet<String>();
            categoryCodes.add(categoryCd);
            String yetd = DateUtils.getDateStrByFormat(DateUtils.getNextDay(new Date(), -1), DateUtils.YYYYMMDD_PATTERN);
            List<BIStoreSaleCateDay> cateDays =  biSaleAmountDaoService.queryStoreCateSaleAmountDay(manDto.getStoreCode(), 
                    categoryCodes, yetd);
            BigDecimal yetdCustAvgPrice = new BigDecimal("0.00");
            BigDecimal yetdSaleAmount = new BigDecimal("0.00");
            Integer yetdSaleVolume = 0;
            if (CollectionUtils.isNotEmpty(cateDays) && null != cateDays.get(0)) {
                BIStoreSaleCateDay yetdCateDay = cateDays.get(0);
                yetdCustAvgPrice = yetdCateDay.getCustAvgPrice();
                yetdSaleAmount = yetdCateDay.getSaleAmount();
                // 昨日销售数量
                yetdSaleVolume = yetdCateDay.getSaleVolume();
            }
            // 昨日客单价
            indexDay.setYetdCustAvgPrice(BiSaleAmountDto.valueOfLow(yetdCustAvgPrice));
            // 昨日销售额  
            indexDay.setYetdSaleAmount(BiSaleAmountDto.valueOf(yetdSaleAmount));
            // 获取昨日品类销冠品牌数据
            BiStoreCateBrandDay yetdMaxBrandDay = biSaleAmountDaoService.queryMaxStoreCateBrandDay(yetd, manDto.getStoreCode(), categoryCd);
            BigDecimal yetdMaxBrandAmount = new BigDecimal("0.00");
            String yetdMaxBrandCode = "";
            String yetdMaxBrandName = "";
            if (null != yetdMaxBrandDay) {
                // 昨日销冠品牌销售额
                yetdMaxBrandAmount = yetdMaxBrandDay.getSaleAmount();
                // 昨日销冠品牌编码
                yetdMaxBrandCode = yetdMaxBrandDay.getBrandCode();
                // 昨日销冠品牌名称 
                yetdMaxBrandName = yetdMaxBrandDay.getBrandName();
            }
            // 昨日销冠品牌销售额
            indexDay.setYetdMaxBrandAmount(BiSaleAmountDto.valueOf(yetdMaxBrandAmount));
            // 昨日销冠品牌编码
            indexDay.setYetdMaxBrandCode(yetdMaxBrandCode);
            // 昨日销冠品牌名称 
            indexDay.setYetdMaxBrandName(yetdMaxBrandName);
            
            // 平均单价
            BigDecimal currCommAvgPrice = BigDecimal.ZERO;
            BigDecimal lastCommAvgPrice = BigDecimal.ZERO;
            String saleRate = "0";
            if (null != realTimeMap && null != realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_COUNT)) {
                currCommAvgPrice = DJStringUtils.divide(todaySaleAmount, 
                        DJStringUtils.bigDecimal(String.valueOf(realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_COUNT))));
            }
            if (null != yetdSaleAmount && null != yetdSaleVolume) {
                lastCommAvgPrice = DJStringUtils.divide(yetdSaleAmount, DJStringUtils.bigDecimal(String.valueOf(yetdSaleVolume)));
            }
            // 同期平均单价
            BigDecimal lastYearCommAvgPrice = BigDecimal.ZERO;
            BigDecimal saleAmountLastYear = biKafkaRealTimeSaleService.queryLastYearStoreCateSaleAmount(
                    manDto.getStoreCode(), cateCode);
            BigDecimal saleCntLastYear = biKafkaRealTimeSaleService.queryLastYearStoreSaleVolume(manDto.getStoreCode(),
                    cateCode);
            if (null != saleAmountLastYear && null != saleCntLastYear) {
                lastYearCommAvgPrice = DJStringUtils.divide(saleAmountLastYear, saleCntLastYear);
            }
            saleRate = DJStringUtils.calculateYoyString(currCommAvgPrice, lastYearCommAvgPrice);
            indexDay.setCommAvgPrice(new BiStoreAvgPrice(BiSaleAmountDto.valueOfLow(currCommAvgPrice), BiSaleAmountDto
                    .valueOfLow(lastCommAvgPrice), saleRate));
					            
            //延保品类销售
            BiStoreYbInfoDto biStoreYbInfoDto = new BiStoreYbInfoDto();
            
            BigDecimal ybAmount = biKafkaRealTimeSaleService.getStoreYbCateSaleFromRedis( manDto.getStoreCode(),categoryCd);
            //门店品类延保销售额
            biStoreYbInfoDto.setSaleAmount(BiSaleAmountDto.valueOf(ybAmount));
            biStoreYbInfoDto.setSaleRate( DJStringUtils.calculateRateString(ybAmount.toString(), saleAmount.toString()));

            indexDay.setYbInfo(biStoreYbInfoDto);
            
            // 销售top单品信息
            indexDay.setTopSaleCmmdty(biCmmdtyService.queryTopSaleCmmdtyByDay(manDto.getStoreCode(), cateCode,
                    DateUtils.getDateStrByFormat(null, DateUtils.YYYYMMDD_PATTERN)));
            
            returnMsg.setData(indexDay);
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return returnMsg;
    }
    
    /**
     * 
     * 功能描述: 获取今日品类品牌销冠<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private Map<String, Object> getTodayMaxBrand(String storeCode, String cateCode) {
        List<Map<String, Object>> maps = biKafkaRealTimeSaleService.getStoreBrandSaleDataFromRedis(storeCode);
        BigDecimal max = null;
        Map<String, Object> maxMap = null;
        for (Map<String, Object> map : maps) {
            String tmpCateCode = (String) map.get(BiRealTimeConstants.StoreCateBrandAttributes.CATE_CODE);
            if (cateCode.equals(tmpCateCode)) {
                if (null != map.get(BiRealTimeConstants.StoreCateBrandAttributes.CATE_CODE)) {
                    BigDecimal tmpSaleAmount = new BigDecimal((Double) map.get(BiRealTimeConstants.StoreCateBrandAttributes.SALE_AMOUNT));
                    if (null == max) {
                        max = tmpSaleAmount;
                        maxMap = map;
                    } else {
                        if (max.compareTo(tmpSaleAmount) < 0) {
                            max = tmpSaleAmount;
                            maxMap = map;
                        }
                    }
                }
            }
        }
        
        return maxMap;
    }
    
    /**
     * 
     * 功能描述: 计算剩余差额<br>
     * 〈功能详细描述〉
     *
     * @param saleAmount
     * @param taskSaleAmount
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private BiSaleAmountDto getSyce(BigDecimal saleAmount, BigDecimal taskSaleAmount) {
        // 如果目标任务额为空，不存在剩余差额
        if (null == taskSaleAmount) {
            return new BiSaleAmountDto("0.00", BiSaleAmountDto.UNIT_WAN);
        }
        BigDecimal syce = taskSaleAmount.subtract(saleAmount);
        if (syce.compareTo(new BigDecimal(0)) < 0) {
            // 实际销售额已经超过任务额，则剩余差额为0
            return new BiSaleAmountDto("0.00", BiSaleAmountDto.UNIT_WAN);
        } else {
            return BiSaleAmountDto.valueOf(syce);
        }
    }
    
    @Override
    public ReturnMsg<StoreGuideIndexMonth> getStoreGuideIndexMonth(String staffId, String cateCode) {
        LOGGER.info("getStoreGuideIndexMonth in staffId:{}， cateCode:{}", staffId, cateCode);
        ReturnMsg<StoreGuideIndexMonth> returnMsg = new ReturnMsg<StoreGuideIndexMonth>();
        // 查询工号对应人员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(staffId);
        // 检验此工号是否为督导，以及cateCode是否属于此人
        if (null != manDto && ClerkConstants.SALE_GUIDE.equals(manDto.getPositionId())
                && CollectionUtils.isNotEmpty(manDto.getCategories())) {
            // 没有传品类编码，默认取此工号的第一个品类
            String categoryCd = StringUtils.isBlank(cateCode) 
                    ? manDto.getCategories().get(0).getCategoryCode() : cateCode;
            if (!manDto.validHasCate(categoryCd)) {
                // 判断品类编码归属于此工号,不属于报参数异常
                returnMsg.setError(ErrorCodeConstants.ERR_0001);
                return returnMsg;
            }
            
            // 参数校验通过，设置督导所属品类信息
            StoreGuideIndexMonth indexMonth = new StoreGuideIndexMonth();
            List<SaleCategory> categories = new ArrayList<SaleCategory>();
            for (Category category : manDto.getCategories()) {
                SaleCategory saleCategory = new SaleCategory();
                saleCategory.setCateCode(category.getCategoryCode());
                saleCategory.setCateName(category.getCategoryName());
                saleCategory.setChooseStatus(categoryCd.equals(category.getCategoryCode())
                        ? SaleCategory.ChooseStatus.YES : SaleCategory.ChooseStatus.NO);
                categories.add(saleCategory);
            }
            indexMonth.setCategories(categories);
            // 当前月份
            String month = DateUtils.getThisMonth();
            StoreCateMonthSaleDataDto monthSaleDto = biSaleAmountDaoService.queryStoreCateMonthSaleData(month, categoryCd, manDto.getStoreCode());
            // 月度销售额 = 截止至昨日的离线销售+今日实时销售
            Map<String, Object> realTimeMap = biKafkaRealTimeSaleService.getStoreCateSaleDataFromRedis(
                    manDto.getStoreCode(), categoryCd);
            // 今日实时销售
            BigDecimal todaySaleAmount = new BigDecimal(0);
            if (null != realTimeMap && null != realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT)) {
                todaySaleAmount = new BigDecimal((Double) realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT));
            }
            BigDecimal saleAmount = todaySaleAmount.add(null != monthSaleDto.getSaleAmount()
                    ? monthSaleDto.getSaleAmount() : new BigDecimal(0));
            // 本月销售额
            indexMonth.setSaleAmount(BiSaleAmountDto.valueOf(saleAmount));
            // 本月任务毛利额
            indexMonth.setTaskGrossProfit(BiSaleAmountDto.valueOf(monthSaleDto.getTaskGrossProfit()));
            // 本月任务销售额
            indexMonth.setTaskSaleAmount(BiSaleAmountDto.valueOf(monthSaleDto.getTaskSaleAmount()));
            // 月度销售完成率
            indexMonth.setSaleCompleteRate(DJStringUtils.calculateRatePercent(saleAmount, monthSaleDto.getTaskSaleAmount()).toString());
            // 月度剩余差额
            indexMonth.setSyce(getSyce(saleAmount, monthSaleDto.getTaskSaleAmount()));
            // 本月客单价
            indexMonth.setCustAvgPrice(BiSaleAmountDto.valueOfLow(monthSaleDto.getCustAvgPrice()));
            // 去年同期客单价
            indexMonth.setLastYearCustAvgPrice(BiSaleAmountDto.valueOfLow(monthSaleDto.getLastYearCustAvgPrice()));
            // 客单价同比
            BigDecimal custAvgPriceYoy = DJStringUtils.calculateYoyPercent(monthSaleDto.getCustAvgPrice(), monthSaleDto.getLastYearCustAvgPrice());
            indexMonth.setCustAvgPriceYoy(null != custAvgPriceYoy ? custAvgPriceYoy.toString() : "");
            // 去年同期销售额
            indexMonth.setLastYearSaleAmount(BiSaleAmountDto.valueOf(monthSaleDto.getLastYearSaleAmount()));
            // 销售额同比
            BigDecimal saleAmountYoy = DJStringUtils.calculateYoyPercent(monthSaleDto.getSaleAmount(), monthSaleDto.getLastYearSaleAmount());
            indexMonth.setSaleAmountYoy(null != saleAmountYoy ? saleAmountYoy.toString() : "");
            // 本月购买人数
            int custNum = 0;
            // 去年同期购买人数
            int lastCustNum = 0;
            if (null != monthSaleDto) {
                if (null != monthSaleDto.getCustNum()) {
                    custNum = monthSaleDto.getCustNum();
                }
                if (null != monthSaleDto.getLastYearCustNum()) {
                    lastCustNum = monthSaleDto.getLastYearCustNum();
                }
            }
            indexMonth.setCustNum(custNum);
            // 去年同期购买人数
            indexMonth.setLastYearCustNum(lastCustNum);
            // 购买人数同比
            BigDecimal custNumYoy = DJStringUtils.calculateYoyPercent(new BigDecimal(custNum), 
                    new BigDecimal(lastCustNum));
            indexMonth.setCustNumYoy(custNumYoy.toString());
            // 品牌销冠数据
            // 去年同期月份
            String lastYearSaleMonth = DateUtils.getLastYearMonthStr();
            StoreMaxSaleBrandMDto brandMDto = biSaleAmountDaoService.queryMaxStoreCateBrandMonth(month, lastYearSaleMonth, manDto.getStoreCode(), categoryCd);
            String lastYearMaxBrandCode = "";
            String lastYearMaxBrandName = "";
            BigDecimal lastYearMaxBrandAmount = new BigDecimal("0.00");
            String maxBrandCode = "";
            String maxBrandName = "";
            BigDecimal maxBrandAmount = new BigDecimal("0.00");
            if (null != brandMDto) {
                // 去年同期销冠品牌编码
                lastYearMaxBrandCode = brandMDto.getLastYearBrandCode();
                // 去年同期销冠品牌名称
                lastYearMaxBrandName = brandMDto.getLastYearBrandName();
                // 去年同期销冠品牌销售额
                lastYearMaxBrandAmount = brandMDto.getLastYearSaleAmount();
                // 本月销冠品牌编码 
                maxBrandCode = brandMDto.getBrandCode();
                // 本月销冠品牌名称
                maxBrandName = brandMDto.getBrandName();
                // 本月销冠品牌销售额
                maxBrandAmount = brandMDto.getSaleAmount();
            }
            // 去年同期销冠品牌编码
            indexMonth.setLastYearMaxBrandCode(lastYearMaxBrandCode);
            // 去年同期销冠品牌名称
            indexMonth.setLastYearMaxBrandName(lastYearMaxBrandName);
            // 去年同期销冠品牌销售额
            indexMonth.setLastYearMaxBrandAmount(BiSaleAmountDto.valueOf(lastYearMaxBrandAmount));
            // 本月销冠品牌编码 
            indexMonth.setMaxBrandCode(maxBrandCode);
            // 本月销冠品牌名称
            indexMonth.setMaxBrandName(maxBrandName);
            // 本月销冠品牌销售额
            indexMonth.setMaxBrandAmount(BiSaleAmountDto.valueOf(maxBrandAmount));
            // 截止昨日日期
            // 月初
            if ("01".equals(DateUtils.getDateStrByFormat(new Date(), "dd"))) {
                indexMonth.setSystemTime("暂未统计");
            } else {
                // 昨日时间
                indexMonth.setSystemTime("截至" + DateUtils.getDateStrByFormat(DateUtils.getNextDay(new Date(), -1), DateUtils.MM_DD_PATTERN));
            }
            
            // 平均单价
            BigDecimal currCommAvgPrice = BigDecimal.ZERO;
            BigDecimal lastCommAvgPrice = BigDecimal.ZERO;
            BigDecimal saleAmountEx = BigDecimal.ZERO;
            BigDecimal saleVolume = BigDecimal.ZERO;
            String saleRate = "0.0";
            if (null != monthSaleDto.getSaleAmount()) {
                saleAmountEx = monthSaleDto.getSaleAmount();
            }
            if (StringUtils.isNotBlank(monthSaleDto.getSaleVolume())) {
                saleVolume = DJStringUtils.bigDecimal(monthSaleDto.getSaleVolume());
            }
            currCommAvgPrice = DJStringUtils.divide(saleAmountEx, saleVolume);
            if (null != monthSaleDto.getLastYearSaleAmount()
                    && StringUtils.isNotBlank(monthSaleDto.getLastYearSaleVolume())) {
                lastCommAvgPrice = DJStringUtils.divide(monthSaleDto.getLastYearSaleAmount(),
                        DJStringUtils.bigDecimal(monthSaleDto.getLastYearSaleVolume()));
            }
            saleRate = DJStringUtils.calculateYoyString(currCommAvgPrice, lastCommAvgPrice);
            indexMonth.setCommAvgPrice(new BiStoreAvgPrice(BiSaleAmountDto.valueOfLow(currCommAvgPrice), BiSaleAmountDto
                    .valueOfLow(lastCommAvgPrice), saleRate));
					
			//设置电器延保
            BiStoreYbInfoDto biStoreYbInfoDto = new BiStoreYbInfoDto();
            BigDecimal ybAmount = biKafkaRealTimeSaleService.getStoreYbCateSaleFromRedis(manDto.getStoreCode(), categoryCd);
            BiStoreYbMonthDto ybMonthSale = biSaleAmountDaoService.queryStoreYbSaleByCate(month, manDto.getStoreCode(),categoryCd);
        
            LOGGER.info("getStoreGuideIndexMonth ybMonthSale={}", ybMonthSale);
            // 当月销售额
            if (null != ybMonthSale && StringUtils.isNotBlank(ybMonthSale.getYbSaleAmount())) {
                ybAmount = ybAmount.add(DJStringUtils.bigDecimal(ybMonthSale.getYbSaleAmount()));
            }
            
            //门店延保销售额
            biStoreYbInfoDto.setSaleAmount(BiSaleAmountDto.valueOf(ybAmount));
            biStoreYbInfoDto.setSaleRate( DJStringUtils.calculateRateString(ybAmount.toString(), saleAmount.toString()));

            indexMonth.setYbInfo(biStoreYbInfoDto);
            
            // 销售top单品信息
            indexMonth.setTopSaleCmmdty(biCmmdtyService.queryTopSaleCmmdtyByMonth(manDto.getStoreCode(), cateCode,
                    DateUtils.getDateStrByFormat(null, DateUtils.YYYYMM_PATTERN)));
            
            returnMsg.setData(indexMonth);
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return returnMsg;
    }

    @Override
    public List<SaleCategory> getBlongGategories(StoreManDto manDto, String cateCode) {
        List<SaleCategory> categories = new ArrayList<SaleCategory>();
        // 没有传品类编码，默认取此工号的第一个品类
        String categoryCd = cateCode;
        if (StringUtils.isBlank(cateCode) && 
                ClerkConstants.SALE_GUIDE.equals(manDto.getPositionId())) {
            categoryCd = manDto.getCategories().get(0).getCategoryCode();
        }
        for (Category category : manDto.getCategories()) {
            SaleCategory saleCategory = new SaleCategory();
            saleCategory.setCateCode(category.getCategoryCode());
            saleCategory.setCateName(category.getCategoryName());
            saleCategory.setChooseStatus(category.getCategoryCode().equals(categoryCd)
                        ? SaleCategory.ChooseStatus.YES : SaleCategory.ChooseStatus.NO);
            categories.add(saleCategory);
        }
        return categories;
    }
    
    @Override
    public List<SaleCategory> getBlongGategoriesAll(StoreManDto manDto, String cateCode) {
        List<SaleCategory> categories = new ArrayList<SaleCategory>();
        // 没有传品类编码，默认取此工号的第一个品类
        String categoryCd = cateCode;
        if (StringUtils.isBlank(cateCode) || CollectionUtils.isEmpty(manDto.getCategories())) {
            return categories;
        }
        for (Category category : manDto.getCategories()) {
            SaleCategory saleCategory = new SaleCategory();
            saleCategory.setCateCode(category.getCategoryCode());
            saleCategory.setCateName(category.getCategoryName());
            saleCategory.setChooseStatus(category.getCategoryCode().equals(categoryCd)
                        ? SaleCategory.ChooseStatus.YES : SaleCategory.ChooseStatus.NO);
            categories.add(saleCategory);
        }
        return categories;
    }

    @Override
    public ReturnMsg<StoreGuideSaleCompleteRate> getStoreCateSaleCompleteRates(String staffId, String year, String cateCode) {
        Object[] args = {staffId, year, cateCode};
        LOGGER.info("getStoreCateSaleCompleteRates in staffId:{}， year：{}， cateCode:{}", args);
        ReturnMsg<StoreGuideSaleCompleteRate> returnMsg = new ReturnMsg<StoreGuideSaleCompleteRate>();        // 查询工号对应人员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(staffId);
        // 检验此工号是否为督导，以及cateCode是否属于此人
        if (null != manDto && ClerkConstants.SALE_GUIDE.equals(manDto.getPositionId())
                && CollectionUtils.isNotEmpty(manDto.getCategories())) {
            // 没有传品类编码，默认取此工号的第一个品类
            String categoryCd = StringUtils.isBlank(cateCode) 
                    ? manDto.getCategories().get(0).getCategoryCode() : cateCode;
            if (!manDto.validHasCate(categoryCd)) {
                // 判断品类编码归属于此工号,不属于报参数异常
                returnMsg.setError(ErrorCodeConstants.ERR_0001);
                return returnMsg;
            }
            
            // 参数校验通过，设置督导所属品类信息
            StoreGuideSaleCompleteRate guideSaleCompleteRate = new StoreGuideSaleCompleteRate();
            List<SaleCategory> categories = new ArrayList<SaleCategory>();
            for (Category category : manDto.getCategories()) {
                SaleCategory saleCategory = new SaleCategory();
                saleCategory.setCateCode(category.getCategoryCode());
                saleCategory.setCateName(category.getCategoryName());
                saleCategory.setChooseStatus(categoryCd.equals(category.getCategoryCode())
                        ? SaleCategory.ChooseStatus.YES : SaleCategory.ChooseStatus.NO);
                categories.add(saleCategory);
            }
            guideSaleCompleteRate.setCategories(categories);
            // 如果year为空则默认查询今年
            String queryYear = year;
            if (StringUtils.isBlank(year)) {
                queryYear = DateUtils.getDateStrByFormat(new Date(), DateUtils.YYYY);
            }
            guideSaleCompleteRate.setYear(queryYear);
            // 查询该门店次品类完成率列表
            List<StoreCateMonthSaleDto> cateSales = biSaleAmountDaoService.queryStoreCateSalesInYear(queryYear, manDto.getStoreCode(), cateCode);
            // 组装数据完成率数据
            List<BiStoreCateSaleCompleteRateDto> completeRates = new ArrayList<BiStoreCateSaleCompleteRateDto>();
            String thisMonth = DateUtils.getThisMonth();
            for (StoreCateMonthSaleDto dto : cateSales) {
                BiStoreCateSaleCompleteRateDto rateDto = new BiStoreCateSaleCompleteRateDto();
                String month = dto.getSaleMonth().substring(0, 4) + "-" + dto.getSaleMonth().substring(4, 6);
                rateDto.setMonth(month);
                if (thisMonth.equals(dto.getSaleMonth())) {
                    // 当月 需要加今日实时销售
                    Map<String, Object> realTimeMap = biKafkaRealTimeSaleService.getStoreCateSaleDataFromRedis(
                            manDto.getStoreCode(), categoryCd);
                    // 今日实时销售
                    BigDecimal todaySaleAmount = new BigDecimal(0);
                    if (null != realTimeMap && null != realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT)) {
                        todaySaleAmount = new BigDecimal((Double) realTimeMap.get(BiRealTimeConstants.StoreCateAttributes.SALE_AMOUNT));
                    }
                    BigDecimal saleAmount = todaySaleAmount.add(null != dto.getSaleAmount() ? dto.getSaleAmount() : new BigDecimal(0));
                    dto.setSaleAmount(saleAmount);
                }
                rateDto.setSaleAmount(BiSaleAmountDto.valueOf(dto.getSaleAmount()));
                rateDto.setTargetSaleAmount(BiSaleAmountDto.valueOf(dto.getTaskSaleAmount()));
                BigDecimal surplus = new BigDecimal("0.00");
                if (null != dto.getTaskSaleAmount()) {
                    surplus = dto.getTaskSaleAmount().subtract(dto.getSaleAmount());
                }
                BigDecimal surplusAmount = surplus.compareTo(new BigDecimal(0)) < 0 ? new BigDecimal("0.00") : surplus;
                rateDto.setSurplusAmount(BiSaleAmountDto.valueOf(surplusAmount));
                BigDecimal rate = DJStringUtils.calculateRatePercent(dto.getSaleAmount(), dto.getTaskSaleAmount());
                rateDto.setRate(null != rate ? rate.toString() : "0.0");
                completeRates.add(rateDto);
            }
            guideSaleCompleteRate.setCompleteRates(completeRates);
            returnMsg.setData(guideSaleCompleteRate);
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return returnMsg;
    }

    @Override
    public ReturnMsg<IndexCockpitDto> getCockpitIndex(String staffId, String cateCode) {
        StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
        ReturnMsg<IndexCockpitDto> returnMsg = new ReturnMsg<IndexCockpitDto>();
        IndexCockpitDto cockpitDto = new IndexCockpitDto();
        // 退货数据
        ReturnMsg<Map<String, Object>> result = biStoreRetGdsHomeService.queryRetGdsHomeInfo(storeMan);
        if (ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            Map<String, Object> map = result.getData();
            @SuppressWarnings("unchecked")
            List<BiStoreRetGdsHomeVo> list = (List<BiStoreRetGdsHomeVo>) map.get("refundInfo");
            IndexCockpitRetGdsDto refund = new IndexCockpitRetGdsDto();
            BigDecimal refundAmount = new BigDecimal("0.00");
            if (CollectionUtils.isNotEmpty(list)) {
                BiStoreRetGdsHomeVo vo = null;
                if (StringUtils.isNotBlank(cateCode)) {
                    for (BiStoreRetGdsHomeVo homeVo : list) {
                        if (cateCode.equals(homeVo.getCategoryCode())) {
                            vo = homeVo;
                        }
                    }
                } else {
                    vo = list.get(0);
                }
                if (null != vo) {
                    refundAmount = vo.getRefund();
                }
            }
            refund.setRefundAmount(BiSaleAmountDto.valueOf(refundAmount));
            cockpitDto.setRefundInfo(refund);
        }
        // 缺货
        ReturnMsg<List<StoreOosHomeShowDto>> oosResult = storeOosService.queryOosHomeDataShow(staffId);
        // 组装两块数据
        if (null != oosResult && ReturnMsg.SUCCESS.equals(oosResult.getRetFlag())) {
            StoreOosHomeShowDto dto = new StoreOosHomeShowDto();
            if (CollectionUtils.isNotEmpty(oosResult.getData())) {
                if (StringUtils.isNotBlank(cateCode)) {
                    for (StoreOosHomeShowDto showDto : oosResult.getData()) {
                        if (cateCode.equals(showDto.getCategoryCode())) {
                            dto = showDto;
                        } 
                    }
                } else {
                    dto = oosResult.getData().get(0);
                }
            }
            if (null == dto.getGeneralOosNum()) {
                dto.setGeneralOosNum(0);
            }
            cockpitDto.setOos(dto);
        }
        // 样机贡献率
        List<SummaryContributionVo> contributionVos = modelAnalyseService.querySummaryContribution(storeMan.getStoreCode(),
                ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId()) ? storeMan.getCategories() : null);
        SummaryContributionVo contributionVo = new SummaryContributionVo();
        if (CollectionUtils.isNotEmpty(contributionVos)) {
            if (StringUtils.isNotBlank(cateCode)) {
                for (SummaryContributionVo showDto : contributionVos) {
                    if (cateCode.equals(showDto.getCateCode())) {
                        contributionVo = showDto;
                    } 
                }
            } else {
                contributionVo = contributionVos.get(0);
            }
        }
        if (null == contributionVo.getRate()) {
            contributionVo.setRate("0.0");
        }
        
        cockpitDto.setContributions(contributionVo);
        
        // 已销未提数据
        // 查询已销未提首页数据
        ReturnMsg<List<CateInfo>> cateList = saledNoTakeService.queryCateInfoByCateCodeList(storeMan);
        IndexCockpitSaleNoPick noPick = null;
        // 组装两块数据
        if (cateList != null && ReturnMsg.SUCCESS.equals(cateList.getRetFlag())) {
            noPick = new IndexCockpitSaleNoPick();
            if (CollectionUtils.isNotEmpty(cateList.getData())) {
                if (StringUtils.isNotBlank(cateCode)) {
                    for (CateInfo showDto : cateList.getData()) {
                        if (cateCode.equals(showDto.getCategoryCode())) {
                            noPick.setOrderNum(showDto.getTotalNum());
                        } 
                    }
                } else {
                    noPick.setOrderNum(cateList.getData().get(0).getTotalNum());
                }
            }
            if (null == noPick.getOrderNum()) {
                noPick.setOrderNum(0);
            }
            cockpitDto.setSaleNoPick(noPick);
        }
        
        returnMsg.setData(cockpitDto);
        return returnMsg;
    }

    /**
     * 月维度查询门店品牌平均单价
     */
    @Override
    public BiStoreSaleBrandAvgPricedDto queryBrandCommAvgPriceByMonth(StoreManDto storeManDto, String cateCode,
            String month) {
        BiStoreSaleBrandAvgPricedDto dto = new BiStoreSaleBrandAvgPricedDto();
        String storeCode = storeManDto.getStoreCode();

        // 销售额
        BigDecimal saleAmount = BigDecimal.ZERO;
        // 销量
        String saleCnt = "0";
        // 平均单价
        BigDecimal commAvgPrice = BigDecimal.ZERO;
        // 平均单价同比
        String saleRate = "0.0";
        // 品牌列表
        List<BiStoreSaleBrandAvgPricedDetailsDto> brandPriceList = new ArrayList<BiStoreSaleBrandAvgPricedDetailsDto>();

        // 转换时间成数据库月份格式
        Date time = DateUtils.getDateByStr(month, "yyyy-MM");
        String monthDb = DateUtils.getDateStrByFormat(time, "yyyyMM");

        // 查询月份品类
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("month", monthDb);
        paramMap.put("storeCode", storeCode);
        paramMap.put("cateCode", cateCode);
        BiStoreCateSaleDayDto cateMonthSale = dalClient.queryForObject(
                "BI_STORE_DATA_WAP.QUERY_STORE_CATE_AMOUNT_RANK_MONTH", paramMap, BiStoreCateSaleDayDto.class);
        if (null != cateMonthSale) {
            if (StringUtils.isNotBlank(cateMonthSale.getSaleAmount())) {
                saleAmount = DJStringUtils.bigDecimal(cateMonthSale.getSaleAmount());
            } else {
                saleAmount = BigDecimal.ZERO;
            }
            if (StringUtils.isNotBlank(cateMonthSale.getSaleVolume())) {
                saleCnt = cateMonthSale.getSaleVolume();
            } else {
                saleCnt = "0";
            }
            commAvgPrice = DJStringUtils.divide(saleAmount, DJStringUtils.bigDecimal(saleCnt));
            if (StringUtils.isNotBlank(cateMonthSale.getLastYearSaleAmount())
                    && StringUtils.isNotBlank(cateMonthSale.getLastYearVolume())) {
                saleRate = DJStringUtils.calculateYoyString(commAvgPrice, DJStringUtils.divide(
                        DJStringUtils.bigDecimal(cateMonthSale.getLastYearSaleAmount()),
                        DJStringUtils.bigDecimal(cateMonthSale.getLastYearVolume())));
            } else {
                saleRate = "0.0";
            }
        }
        // 查询下属品牌信息
        List<BiBrandSale> brandList = biBrandDaoService.queryBrandSaleByMonth(cateCode, month,
                storeManDto.getStoreCode(), ORDER_BY_AMOUNT);
        String brandCode;
        String brandName;
        // 品牌销售额
        BigDecimal brandSaleAmount;
        // 品牌销售数量
        String brandSaleCnt;
        // 品牌平均单价
        BigDecimal brandAvgPrice;
        // 品牌销售额同比
        String brandRate;
        if (CollectionUtils.isNotEmpty(brandList)) {
            for (BiBrandSale sale : brandList) {
                brandCode = sale.getBrandCode();
                brandName = sale.getBrandName();
                if (StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                    continue;
                }
                if (null != sale.getBrandAmount()) {
                    brandSaleAmount = sale.getBrandAmount();
                } else {
                    brandSaleAmount = BigDecimal.ZERO;
                }
                if (null != sale.getSaleCnt()) {
                    brandSaleCnt = String.valueOf(sale.getSaleCnt());
                } else {
                    brandSaleCnt = "0";
                }
                brandAvgPrice = DJStringUtils.divide(brandSaleAmount, DJStringUtils.bigDecimal(brandSaleCnt));
                // 计算平均单价同比
                if (null != sale.getBrandAmountLy() && null != sale.getBrandCntLy()) {
                    brandRate = DJStringUtils.calculateYoyString(brandAvgPrice,
                            DJStringUtils.divide(sale.getBrandAmountLy(), sale.getBrandCntLy()));
                } else {
                    brandRate = "0.0";
                }
                brandPriceList.add(new BiStoreSaleBrandAvgPricedDetailsDto(brandCode, brandName, brandRate,
                        BiSaleAmountDto.valueOf(brandSaleAmount), DJStringUtils.transIntergerStr(brandSaleCnt), BiSaleAmountDto
                                .valueOfLow(brandAvgPrice)));
            }
        }

        dto.setCommAvgPrice(BiSaleAmountDto.valueOfLow(commAvgPrice));
        dto.setSaleAmount(BiSaleAmountDto.valueOf(saleAmount));
        dto.setSaleCnt(DJStringUtils.transIntergerStr(saleCnt));
        dto.setSaleRate(saleRate);
        // 根据平均单价进行排序
        if (CollectionUtils.isNotEmpty(brandPriceList)) {
            Collections.sort(brandPriceList, new Comparator<BiStoreSaleBrandAvgPricedDetailsDto>() {
                @Override
                public int compare(BiStoreSaleBrandAvgPricedDetailsDto o1, BiStoreSaleBrandAvgPricedDetailsDto o2) {
                    BigDecimal avgPrice1 = o1.getBrandAvgPrice().getSortMoney();
                    BigDecimal avgPrice2 = o2.getBrandAvgPrice().getSortMoney();
                    if (null != avgPrice1 && null != avgPrice2) {
                        return avgPrice2.compareTo(avgPrice1);
                    } else if (null == avgPrice2) {
                        return -1;
                    } else if (null == avgPrice1) {
                        return 1;
                    }
                    // 降序
                    return 0;
                }
            });
            // 品牌只显示前20个
            for (List<BiStoreSaleBrandAvgPricedDetailsDto> newList : Lists
                    .partition(brandPriceList, BRAND_MAX_SHOW_NUM)) {
                brandPriceList = newList;
                break;
            }
        }
        dto.setList(brandPriceList);
        List<SaleCategory> categories = new ArrayList<SaleCategory>();
        SaleCategory saleCategory;
        for (Category category : storeManDto.getCategories()) {
            saleCategory = new SaleCategory();
            saleCategory.setCateCode(category.getCategoryCode());
            saleCategory.setCateName(category.getCategoryName());
            saleCategory.setChooseStatus(cateCode.equals(category.getCategoryCode()) ? SaleCategory.ChooseStatus.YES
                    : SaleCategory.ChooseStatus.NO);
            categories.add(saleCategory);
        }
        dto.setCategories(categories);
        return dto;
    }

    /**
     * 日维度查询门店品牌平均单价
     */
    @Override
    public BiStoreSaleBrandAvgPricedDto queryBrandCommAvgPriceByDay(StoreManDto storeManDto, String cateCode,
            String date) {
        BiStoreSaleBrandAvgPricedDto dto = new BiStoreSaleBrandAvgPricedDto();
        List<BiStoreSaleBrandAvgPricedDetailsDto> brandPriceList = new ArrayList<BiStoreSaleBrandAvgPricedDetailsDto>();
        
        // 销售额
        BigDecimal saleAmount = BigDecimal.ZERO;
        // 销量
        String saleCnt = "0";
        // 平均单价
        BigDecimal commAvgPrice = BigDecimal.ZERO;
        // 平均单价同比
        String saleRate = "0.0";

        // 判断是否是查询今天的平均单价
        if (DateUtils.getDateStrByFormat(null, "yyyy-MM-dd").equals(date)) {
            // 查询品类实时数据
            Map<String, Object> cateSaleReal = biKafkaRealTimeSaleService.getStoreCateSaleDataFromRedis(
                    storeManDto.getStoreCode(), cateCode);
            if (null != cateSaleReal) {
                if (null != cateSaleReal.get("payAmt")) {
                    saleAmount = DJStringUtils.bigDecimal(String.valueOf(cateSaleReal.get("payAmt")));
                } else {
                    saleAmount = BigDecimal.ZERO;
                }
                if (null != cateSaleReal.get("saleCnt")) {
                    saleCnt = String.valueOf(cateSaleReal.get("saleCnt"));
                } else {
                    saleCnt = "0";
                }
                commAvgPrice = DJStringUtils.divide(saleAmount, DJStringUtils.bigDecimal(saleCnt));
            }
            BigDecimal saleAmountLastYear = biKafkaRealTimeSaleService.queryLastYearStoreCateSaleAmount(storeManDto.getStoreCode(), cateCode);
            BigDecimal saleCntLastYear =  biKafkaRealTimeSaleService.queryLastYearStoreSaleVolume(storeManDto.getStoreCode(), cateCode);
            if (null != saleAmountLastYear && null != saleCntLastYear) {
                saleRate = DJStringUtils.calculateYoyString(commAvgPrice,
                        DJStringUtils.divide(saleAmountLastYear, saleCntLastYear));
            } else {
                saleRate = "0.0";
            }
            // 查询品类下品牌实时数据
            List<BiBrandSale> brandList = biBrandService.getBrandSaleByDay(cateCode, ORDER_BY_AMOUNT,
                    storeManDto.getStoreCode());
            if (CollectionUtils.isNotEmpty(brandList)) {
                String brandCode;
                String brandName;
                // 品牌销售额
                BigDecimal brandSaleAmount;
                // 品牌销售数量
                String brandSaleCnt;
                // 品牌平均单价
                BigDecimal brandAvgPrice;
                // 品牌平均价同比
                String brandRate;
                for (BiBrandSale sale : brandList) {
                    brandCode = sale.getBrandCode();
                    brandName = sale.getBrandName();
                    if (StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                        continue;
                    }
                    if (null != sale.getBrandAmount()) {
                        brandSaleAmount = sale.getBrandAmount();
                    } else {
                        brandSaleAmount = BigDecimal.ZERO;
                    }
                    if (null != sale.getSaleCnt()) {
                        brandSaleCnt = String.valueOf(sale.getSaleCnt());
                    } else {
                        brandSaleCnt = "0";
                    }
                    brandAvgPrice = DJStringUtils.divide(brandSaleAmount, DJStringUtils.bigDecimal(brandSaleCnt));
                    // 计算平均单价同比
                    if (null != sale.getBrandAmountLy() && null != sale.getBrandCntLy()) {
                        brandRate = DJStringUtils.calculateYoyString(brandAvgPrice,
                                DJStringUtils.divide(sale.getBrandAmountLy(), sale.getBrandCntLy()));
                    } else {
                        brandRate = "0.0";
                    }
                    brandPriceList.add(new BiStoreSaleBrandAvgPricedDetailsDto(brandCode, brandName, brandRate,
                            BiSaleAmountDto.valueOf(brandSaleAmount), DJStringUtils.transIntergerStr(brandSaleCnt),
                            BiSaleAmountDto.valueOfLow(brandAvgPrice)));
                }
            }

        } else {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            Date time = DateUtils.getDateByStr(date, "yyyy-MM-dd");
            paramMap.put("storeCode", storeManDto.getStoreCode());
            paramMap.put("day", DateUtils.getDateStrByFormat(time, "yyyyMMdd"));
            paramMap.put("cates", cateCode);
            // 查询品类
            List<BiStoreCateSaleDataDayDto> cateSales = dalClient.queryForList(
                    "BI_STORE_DATA_WAP.QUERY_STORE_CATE_DATA_BY_DAY", paramMap, BiStoreCateSaleDataDayDto.class);
            if (CollectionUtils.isNotEmpty(cateSales)) {
                BiStoreCateSaleDataDayDto cateInfo = cateSales.get(FIRST_ELE);
                if (StringUtils.isNotBlank(cateInfo.getSaleAmount())) {
                    saleAmount = DJStringUtils.bigDecimal(cateInfo.getSaleAmount());
                } else {
                    saleAmount = BigDecimal.ZERO;
                }
                if (StringUtils.isNotBlank(cateInfo.getSaleVolume())) {
                    saleCnt = cateInfo.getSaleVolume();
                } else {
                    saleCnt = "0";
                }
                if (StringUtils.isNotBlank(cateInfo.getSaleAmount())
                        && StringUtils.isNotBlank(cateInfo.getSaleVolume())) {
                    commAvgPrice = DJStringUtils.divide(saleAmount, DJStringUtils.bigDecimal(saleCnt));
                } else {
                    commAvgPrice = BigDecimal.ZERO;
                }
                if (StringUtils.isNotBlank(cateInfo.getLastYearSaleAmount())
                        && StringUtils.isNotBlank(cateInfo.getLastYearVolume())) {
                    BigDecimal commAvgPriceLastYear = DJStringUtils.divide(
                            DJStringUtils.bigDecimal(cateInfo.getLastYearSaleAmount()),
                            DJStringUtils.bigDecimal(cateInfo.getLastYearVolume()));
                    saleRate = DJStringUtils.calculateYoyString(commAvgPrice, commAvgPriceLastYear);
                } else {
                    saleRate = "0";
                }
            }
            // 查询品类下品牌
            List<BiBrandSale> brandList = biBrandDaoService.queryBrandSaleByDay(cateCode, date,
                    storeManDto.getStoreCode(), ORDER_BY_AMOUNT);
            if (CollectionUtils.isNotEmpty(brandList)) {
                String brandCode;
                String brandName;
                // 品牌销售额
                BigDecimal brandSaleAmount;
                // 品牌销售数量
                String brandSaleCnt;
                // 品牌平均单价
                BigDecimal brandAvgPrice;
                // 品牌平均价同比
                String brandRate;
                for (BiBrandSale sale : brandList) {
                    brandCode = sale.getBrandCode();
                    brandName = sale.getBrandName();
                    if (StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                        continue;
                    }
                    if (null != sale.getBrandAmount()) {
                        brandSaleAmount = sale.getBrandAmount();
                    } else {
                        brandSaleAmount = BigDecimal.ZERO;
                    }
                    if (null != sale.getSaleCnt()) {
                        brandSaleCnt = String.valueOf(sale.getSaleCnt());
                    } else {
                        brandSaleCnt = "0";
                    }
                    brandAvgPrice = DJStringUtils.divide(brandSaleAmount, DJStringUtils.bigDecimal(brandSaleCnt));
                    // 计算平均价同比
                    if (null != sale.getBrandAmountLy() && null != sale.getBrandCntLy()) {
                        brandRate = DJStringUtils.calculateYoyString(brandAvgPrice,
                                DJStringUtils.divide(sale.getBrandAmountLy(), sale.getBrandCntLy()));
                    } else {
                        brandRate = "0.0";
                    }
                    brandPriceList.add(new BiStoreSaleBrandAvgPricedDetailsDto(brandCode, brandName, brandRate,
                            BiSaleAmountDto.valueOf(brandSaleAmount), DJStringUtils.transIntergerStr(brandSaleCnt),
                            BiSaleAmountDto.valueOfLow(brandAvgPrice)));
                }
            }

        }

        dto.setCommAvgPrice(BiSaleAmountDto.valueOfLow(commAvgPrice));
        dto.setSaleAmount(BiSaleAmountDto.valueOf(saleAmount));
        dto.setSaleCnt(DJStringUtils.transIntergerStr(saleCnt));
        dto.setSaleRate(saleRate);
        // 根据平均单价进行排序
        if (CollectionUtils.isNotEmpty(brandPriceList)) {
            Collections.sort(brandPriceList, new Comparator<BiStoreSaleBrandAvgPricedDetailsDto>() {
                @Override
                public int compare(BiStoreSaleBrandAvgPricedDetailsDto o1, BiStoreSaleBrandAvgPricedDetailsDto o2) {
                    BigDecimal avgPrice1 = o1.getBrandAvgPrice().getSortMoney();
                    BigDecimal avgPrice2 = o2.getBrandAvgPrice().getSortMoney();
                    if (null != avgPrice1 && null != avgPrice2) {
                        return avgPrice2.compareTo(avgPrice1);
                    } else if (null == avgPrice2) {
                        return -1;
                    } else if (null == avgPrice1) {
                        return 1;
                    }
                    // 降序
                    return 0;
                }
            });
            // 品牌只显示前20个
            for (List<BiStoreSaleBrandAvgPricedDetailsDto> newList : Lists
                    .partition(brandPriceList, BRAND_MAX_SHOW_NUM)) {
                brandPriceList = newList;
                break;
            }
        }
        dto.setList(brandPriceList);
        List<SaleCategory> categories = new ArrayList<SaleCategory>();
        SaleCategory saleCategory;
        for (Category category : storeManDto.getCategories()) {
            saleCategory = new SaleCategory();
            saleCategory.setCateCode(category.getCategoryCode());
            saleCategory.setCateName(category.getCategoryName());
            saleCategory.setChooseStatus(cateCode.equals(category.getCategoryCode()) ? SaleCategory.ChooseStatus.YES
                    : SaleCategory.ChooseStatus.NO);
            categories.add(saleCategory);
        }
        dto.setCategories(categories);

        return dto;
    }
    
	 @Override
    public BiStoreJxcCateInfo queryBrandJxcByDate(StoreManDto storeManDto, String day, String cateCode) {
        LOGGER.info("enter queryBrandJxcByDate, storeCode={},day={}", storeManDto.getStoreCode(), day);
        
        // 判断是否是查询今天的销售排行
        if (DateUtils.getDateStrByFormat(null, "yyyy-MM-dd").equals(day)) {
            // 当日品类销售数据
            Map<String, Object> cateTodaySale = biKafkaRealTimeSaleService.getStoreCateSaleDataFromRedis(storeManDto.getStoreCode(), cateCode);
            //当日品类门店销售额
            BigDecimal totalCateAmount;
            if (null == cateTodaySale || null == cateTodaySale.get("payAmt")) {
                totalCateAmount = BigDecimal.ZERO;
            } else {
                totalCateAmount = DJStringUtils.bigDecimal(String.valueOf(cateTodaySale.get("payAmt")));
            }
          //当日品类进销差销售额
            BigDecimal jxcCateAmount;
            if (null == cateTodaySale || null == cateTodaySale.get("jxc_amount")) {
                jxcCateAmount = BigDecimal.ZERO;
            } else {
                jxcCateAmount = DJStringUtils.bigDecimal(String.valueOf(cateTodaySale.get("jxc_amount")));
            }
            
            // 品类去年同期销售金额
            Map<String, Object> cateLasYearSale = biKafkaRealTimeSaleService.queryLastYearStoreCateSaleAmountEx(storeManDto.getStoreCode(),cateCode);
            
            //去年同期门店进销差销售额
            BigDecimal lastYearCateJxcAmount;
            if (null == cateLasYearSale || null == cateLasYearSale.get("JXC_AMOUNT")) {
                lastYearCateJxcAmount = BigDecimal.ZERO;
            } else {
                lastYearCateJxcAmount = DJStringUtils.bigDecimal(String.valueOf(cateLasYearSale.get("JXC_AMOUNT")));
            }
            
            BiStoreJxcCateInfo biStoreJxcCateInfo = new BiStoreJxcCateInfo();
            //门店进销差销售额
            biStoreJxcCateInfo.setCateJxcAmount(BiSaleAmountDto.valueOf(jxcCateAmount));
            //门店销售额
            biStoreJxcCateInfo.setCateSaleAmount(BiSaleAmountDto.valueOf(totalCateAmount));
            //进销差率
            biStoreJxcCateInfo.setCateSaleJxcRate(DJStringUtils.calculateRateString(jxcCateAmount.toString(), totalCateAmount.toString()));
            //进销差同比
            biStoreJxcCateInfo.setCateSaleRate(DJStringUtils.calculateYoyString(jxcCateAmount, lastYearCateJxcAmount));
            
            List<SaleCategory> cateList = getBlongGategoriesAll(storeManDto, cateCode);
            biStoreJxcCateInfo.setCateList(cateList);
            
            // 查询门店品牌实时销售数据
            List<Map<String, Object>> brandSales = biKafkaRealTimeSaleService.getStoreBrandSaleDataByCateFromRedis(storeManDto.getStoreCode(), cateCode);
            List<BiStoreJxcBrandDetail> resultList = new ArrayList<BiStoreJxcBrandDetail>();
            // 数据不为空时
            if (CollectionUtils.isEmpty(brandSales)) {
                biStoreJxcCateInfo.setList(resultList);
                return biStoreJxcCateInfo;
            }

            // 根据销售额排序
            Collections.sort(brandSales, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if (null != o2.get("jxc_amount") && null != o1.get("jxc_amount")) {
                        return DJStringUtils.bigDecimal(String.valueOf(o2.get("jxc_amount"))).compareTo(DJStringUtils.bigDecimal(String.valueOf(o1.get("jxc_amount"))));
                    } else if (null == o2.get("jxc_amount")) {
                        return -1;
                    } else if (null == o1.get("jxc_amount")) {
                        return 1;
                    }
                    // 降序
                    return 0;
                }
            });
            //取进销差销售额前二十
            if(brandSales.size() >= 20){
                brandSales  = brandSales.subList(0, 20);
            }
            
            //设置品类详情
            for (Map<String, Object> sale : brandSales) {
                // 获取品牌编码
                String brandCode = String.valueOf(sale.get("brandCd"));
                String brandName =  String.valueOf(sale.get("brandName"));
                // 判断品牌编码和品牌名称是否为空
                if (StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                    // 如果品类编码,或者品类名称不存在,则不处理该品类信息
                    continue;
                }
                BiStoreJxcBrandDetail brandDetail = new BiStoreJxcBrandDetail();
                brandDetail.setBrandCode(brandCode);
                brandDetail.setBrandName(brandName);
                //品牌销售额
                BigDecimal brandSaleAmount;
                if (null != sale.get("payAmt")) {
                    brandSaleAmount = DJStringUtils.bigDecimal(String.valueOf(sale.get("payAmt")));
                } else {
                    brandSaleAmount = BigDecimal.ZERO;
                }
                
                //品牌进销差销售额
                BigDecimal brandJxcAmount;
                if (null != sale.get("jxc_amount")) {
                    brandJxcAmount = DJStringUtils.bigDecimal(String.valueOf(sale.get("jxc_amount")));
                } else {
                    brandJxcAmount = BigDecimal.ZERO;
                }
                
                //延保品类销售额
                brandDetail.setBrandSaleAmount(BiSaleAmountDto.valueOf(brandSaleAmount));
                brandDetail.setBrandJxcAmount(BiSaleAmountDto.valueOf(brandJxcAmount));
                // 进销差率
                brandDetail.setBrandJxcRate(DJStringUtils.calculateRateString(brandJxcAmount.toString(), brandSaleAmount.toString()));
                //进销差同比
                brandDetail.setBrandRate("0.0");
                
                resultList.add(brandDetail);
            }
            biStoreJxcCateInfo.setList(resultList);
            return biStoreJxcCateInfo;
        } else {
            //日销售数据
            Date time = DateUtils.getDateByStr(day, "yyyy-MM-dd");
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("storeCode", storeManDto.getStoreCode());
            paramMap.put("cateCode", cateCode);
            paramMap.put("day", DateUtils.getDateStrByFormat(time, "yyyyMMdd"));
            BiStoreSaleDayDto cateSotalSale = dalClient.queryForObject("BI_STORE_DATA_WAP.QUERY_STORE_CATE_AMOUNT_BY_DAY",
                    paramMap, BiStoreSaleDayDto.class);
            //品类日总销售额
            BigDecimal totalCateAmount;
            if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getSaleAmount())) {
                totalCateAmount = BigDecimal.ZERO;
            } else {
                totalCateAmount = DJStringUtils.bigDecimal(cateSotalSale.getSaleAmount());
            }
            
            //品类日进销差销售额
            BigDecimal jxcCateAmount;
            if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getJxcAmount())) {
                jxcCateAmount = BigDecimal.ZERO;
            } else {
                jxcCateAmount = DJStringUtils.bigDecimal(cateSotalSale.getJxcAmount());
            }
            
            //品类日往期进销差销售额
            BigDecimal lastYearJxcCateAmount;
            if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getLastYearJxcAmount())) {
                lastYearJxcCateAmount = BigDecimal.ZERO;
            } else {
                lastYearJxcCateAmount = DJStringUtils.bigDecimal(cateSotalSale.getLastYearJxcAmount());
            }
            
            BiStoreJxcCateInfo biStoreJxcCateInfo = new BiStoreJxcCateInfo();
            //品类进销差销售额
            biStoreJxcCateInfo.setCateJxcAmount(BiSaleAmountDto.valueOf(jxcCateAmount));
            //品类销售额
            biStoreJxcCateInfo.setCateSaleAmount(BiSaleAmountDto.valueOf(totalCateAmount));
            //品类进销差率
            biStoreJxcCateInfo.setCateSaleJxcRate(DJStringUtils.calculateRateString(jxcCateAmount.toString(), totalCateAmount.toString()));
            //品类进销差同比
            biStoreJxcCateInfo.setCateSaleRate(DJStringUtils.calculateYoyString(jxcCateAmount, lastYearJxcCateAmount));
            
            
            List<SaleCategory> cateList = getBlongGategoriesAll(storeManDto, cateCode);
            biStoreJxcCateInfo.setCateList(cateList);
            //日品牌销售列表
            List<BiBrandSale> brandSaleList = dalClient.queryForList("BI_BRAND_SQL.QUERY_STORE_BRAND_SALE_DAY_LIST",
                    paramMap, BiBrandSale.class);
            List<BiStoreJxcBrandDetail> resultList = new ArrayList<BiStoreJxcBrandDetail>();
            
            if(CollectionUtils.isEmpty(brandSaleList)){
                biStoreJxcCateInfo.setList(resultList);
                return biStoreJxcCateInfo;
            }
            
            for(BiBrandSale item  : brandSaleList){
                if(item == null){
                    continue;
                }
                // 获取品牌编码
                String brandCode = item.getBrandCode();
                String brandName = item.getBrandName();
                
                // 判断品牌编码和品牌名称是否为空
                if ( StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                    // 如果品牌编码,或者品类名称不存在,则不处理该品类信息
                    continue;
                }
                
                BiStoreJxcBrandDetail brandDetail = new BiStoreJxcBrandDetail();
                brandDetail.setBrandCode(brandCode);
                brandDetail.setBrandName(brandName);
                //品牌销售额
                BigDecimal brandSaleAmount;
                if (null == item || item.getBrandAmount() == null ) {
                    brandSaleAmount = BigDecimal.ZERO;
                } else {
                    brandSaleAmount =item.getBrandAmount();
                }
                
                //品牌进销差销售额
                BigDecimal brandJxcAmount;
                if (null == item || StringUtils.isBlank(item.getJxcAmount())) {
                    brandJxcAmount = BigDecimal.ZERO;
                } else {
                    brandJxcAmount = DJStringUtils.bigDecimal(item.getJxcAmount());
                }
                
                //去年同期品牌进销差
                BigDecimal lastYearBrandJxcAmount;
                if (null == item || StringUtils.isBlank(item.getLastYearJxcAmount())) {
                    lastYearBrandJxcAmount = BigDecimal.ZERO;
                } else {
                    lastYearBrandJxcAmount = DJStringUtils.bigDecimal(item.getLastYearJxcAmount());
                }
                
                //延保品牌销售额
                brandDetail.setBrandSaleAmount(BiSaleAmountDto.valueOf(brandSaleAmount));
                brandDetail.setBrandJxcAmount(BiSaleAmountDto.valueOf(brandJxcAmount));
                //进销差率
                brandDetail.setBrandJxcRate(DJStringUtils.calculateRateString(brandJxcAmount.toString(), brandSaleAmount.toString()));
                //进销差同比
                brandDetail.setBrandRate(DJStringUtils.calculateYoyString(brandJxcAmount, lastYearBrandJxcAmount));
                
                resultList.add(brandDetail);
            }
            biStoreJxcCateInfo.setList(resultList);
            return biStoreJxcCateInfo;
        }
    }

    /**
     * 获取月维度进销差销售，月份品牌销售数据无法获取实时数据
     */
    @Override
    public BiStoreJxcCateInfo queryBrandJxcByMonth(StoreManDto storeManDto, String month, String cateCode) {

        LOGGER.info("enter queryBrandJxcByMonth, storeCode={},day={}", storeManDto.getStoreCode(), month);
        
        Date time = DateUtils.getDateByStr(month, "yyyy-MM");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeManDto.getStoreCode());
        paramMap.put("cateCode", cateCode);
        paramMap.put("month", DateUtils.getDateStrByFormat(time, "yyyyMM"));
        BiStoreSaleDayDto cateSotalSale = dalClient.queryForObject("BI_STORE_DATA_WAP.QUERY_STORE_CATE_AMOUNT_BY_MONTH",
                paramMap, BiStoreSaleDayDto.class);
        //品类月总销售额
        BigDecimal totalCateAmount;
        if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getSaleAmount())) {
            totalCateAmount = BigDecimal.ZERO;
        } else {
            totalCateAmount =DJStringUtils.bigDecimal(cateSotalSale.getSaleAmount());
        }
        
        //品类月进销差销售额
        BigDecimal jxcCateAmount;
        if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getJxcAmount())) {
            jxcCateAmount = BigDecimal.ZERO;
        } else {
            jxcCateAmount = DJStringUtils.bigDecimal(cateSotalSale.getJxcAmount());
        }
        
        //品类月往期进销差销售额
        BigDecimal lastYearJxcCateAmount;
        if (null == cateSotalSale || StringUtils.isBlank(cateSotalSale.getLastYearJxcAmount())) {
            lastYearJxcCateAmount = BigDecimal.ZERO;
        } else {
            lastYearJxcCateAmount = DJStringUtils.bigDecimal(cateSotalSale.getLastYearJxcAmount());
        }  
        
        BiStoreJxcCateInfo biStoreJxcCateInfo = new BiStoreJxcCateInfo();
        //门店进销差销售额
        biStoreJxcCateInfo.setCateJxcAmount(BiSaleAmountDto.valueOf(jxcCateAmount));
        //门店销售额
        biStoreJxcCateInfo.setCateSaleAmount(BiSaleAmountDto.valueOf(totalCateAmount));
        //进销差率
        biStoreJxcCateInfo.setCateSaleJxcRate(DJStringUtils.calculateRateString(jxcCateAmount.toString(), totalCateAmount.toString()));
        //进销差同比
        biStoreJxcCateInfo.setCateSaleRate(DJStringUtils.calculateYoyString(jxcCateAmount, lastYearJxcCateAmount));
        
        List<SaleCategory> cateList = getBlongGategoriesAll(storeManDto, cateCode);
        biStoreJxcCateInfo.setCateList(cateList);
        
        //月品牌销售列表
        List<BiBrandSale> brandSaleList = dalClient.queryForList("BI_BRAND_SQL.QUERY_STORE_BRAND_SALE_MONTH_LIST",
                paramMap, BiBrandSale.class);
        List<BiStoreJxcBrandDetail> resultList = new ArrayList<BiStoreJxcBrandDetail>();
        
        // 数据不为空时
        if (CollectionUtils.isEmpty(brandSaleList)) {
            biStoreJxcCateInfo.setList(resultList);
            return biStoreJxcCateInfo;
        }

        //设置品类详情
        for (BiBrandSale item : brandSaleList) {
            if(item == null){
                continue;
            }
            // 获取品牌编码
            String brandCode = item.getBrandCode();
            String brandName = item.getBrandName();
            
            // 判断品牌编码和品牌名称是否为空
            if ( StringUtils.isBlank(brandCode) || StringUtils.isBlank(brandName)) {
                // 如果品牌编码,或者品类名称不存在,则不处理该品类信息
                continue;
            }
            
            BiStoreJxcBrandDetail brandDetail = new BiStoreJxcBrandDetail();
            brandDetail.setBrandCode(brandCode);
            brandDetail.setBrandName(brandName);
            //品牌销售额
            BigDecimal brandSaleAmount;
            if (null == item || item.getBrandAmount() == null ) {
                brandSaleAmount = BigDecimal.ZERO;
            } else {
                brandSaleAmount =item.getBrandAmount();
            }
            
            //品牌进销差销售额
            BigDecimal brandJxcAmount;
            if (null == item || StringUtils.isBlank(item.getJxcAmount())) {
                brandJxcAmount = BigDecimal.ZERO;
            } else {
                brandJxcAmount = DJStringUtils.bigDecimal(item.getJxcAmount());
            }
            
            //去年同期品牌进销差
            BigDecimal lastYearBrandJxcAmount;
            if (null == item || StringUtils.isBlank(item.getLastYearJxcAmount())) {
                lastYearBrandJxcAmount = BigDecimal.ZERO;
            } else {
                lastYearBrandJxcAmount = DJStringUtils.bigDecimal(item.getLastYearJxcAmount());
            }
            
            //延保品牌销售额
            brandDetail.setBrandSaleAmount(BiSaleAmountDto.valueOf(brandSaleAmount));
            brandDetail.setBrandJxcAmount(BiSaleAmountDto.valueOf(brandJxcAmount));
            //进销差率
            brandDetail.setBrandJxcRate(DJStringUtils.calculateRateString(brandJxcAmount.toString(), brandSaleAmount.toString()));
            //进销差同比
            brandDetail.setBrandRate(DJStringUtils.calculateYoyString(brandJxcAmount, lastYearBrandJxcAmount));
            resultList.add(brandDetail);
        }
        biStoreJxcCateInfo.setList(resultList);
        return biStoreJxcCateInfo;
    }
}
